var Chat = {
	flag1 : false,
	Initial : function(){
		Chat.ReAdjust();		
		$("#chatbox").find("._close").click(function(){
			Ajax.Request({mod:"user",op:"CloseChat"},function(){
				$("#chatbox").fadeOut("slow");
			},false);
		});
		var myform = new FormWatcher($("#chatbox").find("form"),Chat.OnSbumit);
		if(!_debug)	window.setInterval(Chat.LoadChatData,5000);
	},
	Show : function(){
		if($("#chatbox").css("display") != "none") return;
		$("#chatbox").fadeIn("slow");
		Chat.ReAdjust();
	},
	ReAdjust : function(){
		if($("#chatbox").css("display") == "none") return;
		var scrollRect = Ajax.scrollWinRect();
		var winRect = Ajax.getWinRect();
		var showLeft = scrollRect.left + winRect.width - 350;
		var showTop = scrollRect.top + winRect.height - 370;
		$("#chatbox").css("left",showLeft + "px");
		$("#chatbox").css("top",showTop + "px");
	},
	OnSbumit : function(){
		var txt = $("#chatbox").find("textarea").val();
		if(txt.length < 1) return;
		var param = {mod:"user",op:"addchat",content:txt};
		Ajax.Request(param,function(json){
			if(json.data === true){
				Chat.flag1 = true;
				Chat.LoadChatData();
			}
		});
		return false;
	},
	LoadChatData : function(){
		Ajax.Request({mod:"user",op:"GetChatContent"},function(json){
			var tpltxt = '<li><div class="time">#{con_time}</div><div class="#{classname}">#{con_content}</div></li>';
			var template = new Template(tpltxt);
			var htmltxt = "";
			var haveReply = false;
			for(var i=0;i<json.data.length;i++){
				var d = json.data[i];
				if(d.con_from == "USER") d.classname = "content1";
				else d.classname = "content2";
				htmltxt += template.Evaluate(d);
				if(d.con_view == 0) haveReply = true;
			}
			$("#chatbox").find("ul.list-chat").html(htmltxt);
			if(Chat.flag1) $("#chatbox").find("textarea").val("");
			Chat.flag1 = false;
			if(haveReply) Chat.Show();
			if($("#chatbox").css("display") != "none") $("#chatbox").find("textarea").focus();
		},false);
	}
};
$(Chat.Initial);
$(window).scroll(Chat.ReAdjust);
$(window).resize(Chat.ReAdjust);	